package com.tc.juc.pack08;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Auther: tianchao
 * @Date: 2021/10/8 23:30
 * @Description:
 */
@Slf4j
public class TestSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //测试submit
        Future<String> result = pool.submit(() -> {
            log.info("睡眠");
            Thread.sleep(2000);
            return "a";
        });
        log.info("获取结果:{}",result.get());
        Callable<String> taskA = ()->{
            Thread.sleep(2000);
            return "A";
        };
        Callable<String> taskB = ()->{
            Thread.sleep(3000);
            return "B";
        };
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(taskA, taskB));
        for (Future<String> future : futures) {
            log.info("不带超时的: {}", future.get());
        }
        futures = pool.invokeAll(Arrays.asList(taskA, taskB),1000,TimeUnit.MILLISECONDS);
        for (Future<String> future : futures) {
            try {
                log.info("带超时的: {}", future.get());
            }catch (CancellationException e){
                e.printStackTrace();
            }

        }
        String s = pool.invokeAny(Arrays.asList(taskA, taskB));
        log.info("不带超时的invokeAny： {}",s);
        try {
            s = pool.invokeAny(Arrays.asList(taskA, taskB),1000,TimeUnit.MILLISECONDS);
            log.info("带超时的invokeAny {}",s);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        pool.shutdown();
    }
}
